package com.example.demo.utils;

import com.example.demo.common.RequestPojo;
import jakarta.servlet.http.HttpServletRequest;

public class RequestUtils {

    public static RequestPojo getIpInfoFromRequest(HttpServletRequest request) {
        RequestPojo info = new RequestPojo();
        info.setIp(getClientIp(request));
        info.setHost(request.getServerName());
        info.setBrowser(getBrowser(request.getHeader("User-Agent")));
        info.setOs(getOs(request.getHeader("User-Agent")));
        info.setProto(request.getProtocol());
        info.setReferer(request.getHeader("Referer"));
        return info;
    }

    public static String getTokenUuidFromAuth(String oauth) {
        if (oauth == null) {
            return "";
        }
        if (oauth.startsWith("Bearer")) {
            return oauth.substring(6).trim();
        }
        return oauth.trim();
    }

    private static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    private static String getBrowser(String userAgent) {
        if (userAgent == null) {
            return "Unknown";
        }
        userAgent = userAgent.toLowerCase();
        if (userAgent.contains("msie") || userAgent.contains("trident")) {
            return "IE";
        }
        if (userAgent.contains("edg")) {
            return "Edge";
        }
        if (userAgent.contains("chrome")) {
            return "Chrome";
        }
        if (userAgent.contains("firefox")) {
            return "Firefox";
        }
        if (userAgent.contains("safari")) {
            return "Safari";
        }
        if (userAgent.contains("opera")) {
            return "Opera";
        }
        return "Unknown";
    }

    private static String getOs(String userAgent) {
        if (userAgent == null) {
            return "Unknown";
        }
        userAgent = userAgent.toLowerCase();
        if (userAgent.contains("windows")) {
            return "Windows";
        }
        if (userAgent.contains("mac")) {
            return "Mac";
        }
        if (userAgent.contains("linux")) {
            return "Linux";
        }
        if (userAgent.contains("android")) {
            return "Android";
        }
        if (userAgent.contains("iphone")) {
            return "iOS";
        }
        return "Unknown";
    }
}
